#include "constants.h";

XfMissionChapterExecute={
	private ["_chapter_succeeded"];
	diag_log "";
	diag_log "=========================================================================";
	diag_log "                             CHAPTER 3                                   ";
	diag_log "=========================================================================";
	diag_log "";
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter3.sqf","XfMissionChapterExecute","Starting Chapter","_last_random_reinforcement","_random_reinf_diff","_reinforcement_power"];
	DM_Mission_Chapter_CanRun = True;
	DM_Mission_Chapter_Runs = True;
	DM_Mission_Chapter_Success = 0;
	call XfMissionChapterSetup;
	_chapter_succeeded = false;
	if (!DM_Mission_Mission_CanRun) exitWith {diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter3.sqf","XfMissionChapterSetup","Mission canceled!"];};

	_random_town = DM_Chapter_Location;
	_random_town_pos = _random_town select XF_MAP_LOCATION_CENTER;
	_random_town_pos_size = _random_town select XF_MAP_LOCATION_SIZE;
	_enemy_soldiers = DM_Target;
	_initial_count = count _enemy_soldiers;
	_go_back = false;
	diag_log Format["(%1)[%2]: %3: %4: %5, %6",diag_tickTime,"chapter3.sqf","XfMissionChapterExecute","Entering the loop",[_initial_count], Time];
	while {DM_Mission_Chapter_CanRun AND DM_Mission_Mission_CanRun} do {
		sleep 10;
		_players_found = false;
		if (X_MP) then {
			_players_found = false;
			{
				if (([(getPos _x), _random_town_pos, _random_town_pos_size] call XfPointInCircle) && isplayer _x) exitWith { _players_found = true; };
			}foreach playableUnits;
		} else {
			_players_found = ([(getPos player), _random_town_pos, _random_town_pos_size] call XfPointInCircle);
		};
		if (!_player_found && _go_back) then {
			_go_back = false;
		};
		if (_player_found && _go_back) then {
			_player_found = false;
		};
		_alive_enemies = 0;
		{
			if (!isnull _x) then {
				if (alive _x) then { _alive_enemies = _alive_enemies + 1;};
			};
		} foreach _enemy_soldiers;
		if (_players_found) then {
			if  (_alive_enemies > (_initial_count / 5)) then {
				if (!_go_back) then {
					"STR_MF_M_HAMMER1_3_ENEMIESBEHIND" call XfMissionMessageToAll;
					_go_back = true;
				};
			} else {
				["OpenTheRoad","", "","",[],"Succeeded"] call XfMissionTask;
				DM_Mission_Chapter_CanRun = false;
				_chapter_succeeded = true;
			};
		};
	};
	if (!isnil "DM_Ammo_Box") then {
		if (count DM_Ammo_Box == 3) then {
			["d_r_box", [DM_Ammo_Box]] call XNetCallEvent;
		};
	};
	if (DM_Mission_Mission_CanRun) then {
		if (_chapter_succeeded) then {
			call XfMissionChapterSuccess;
		} else {
			call XfMissionChapterFailure;
		};
	} else {
		diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter3.sqf","XfMissionChapterExecute","Mission canceled!"];
	};
	sleep 15;
	// Just in case a reinforcement is already on the way.
	call XfMissionChapterCleanUp;
	DM_Mission_Chapter_Runs = False;
};

XfMissionChapterSetup={
	private ["_random_town","_random_town_pos","_random_town_pos_size","_troops_power","_troops_coeff","_grpSpecOps","_i","_k"];
	diag_log Format["(%1)[%2]: %3; %4 %5",diag_tickTime,"chapter3.sqf","XfMissionChapterSetup","Starting Initialization:",DM_Mission_Name];
	
	_path = DM_Chapter_Data;
	
	// Camp empty vehicles
	_branca_camp_vecs =[
		[[15633.7,17308.6,0],182.206], // Armor
		[[15654.3,17304.9,0],185.118], // Armor
		[[15674.6,17307,0],181.861], // Armor
		[[15673.4,17342.7,0],91.5791], // Jackal
		[[15687.3,17351.1,0],196.051], // Humvee
		[[15695,17351.3,0],186.862], // Humvee
		[[15723.1,17345.4,0],280.04], // Humvee
		[[15717.4,17338.9,0],2.21753], // Humvee
		[[15708.2,17338.9,0],9.84697] // Humvee
	];
	
	_branca_camp_heli =[
		[[15619.3,17244.8,0],185.66],
		[[15656.3,17244.8,0],180.922],
		[[15692.1,17244.9,0],184.508]
	];

	// Gate vehicle
	_branca_gate_vec =[
		[[15643,17364.5,0],96.3666]
	];
	
	_branca_ammo = [15633.4,17345.8,0];
	
	// Destination camp branca
	_parameters = [d_map_locations];
	_parameters set [count _parameters, [XF_MAP_LOCATION_UNIQUENAME,"==","CampBranca"]];
	_eligible_towns = _parameters call XfTableFilter;
	if ((count _eligible_towns) <= 0) exitWith {"STR_MF_RANDOMSITEFAILED" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	_camp_branca = _eligible_towns select 0;
	_camp_branca_pos = _camp_branca select XF_MAP_LOCATION_CENTER;
	_camp_branca_size = _camp_branca select XF_MAP_LOCATION_SIZE;
	_camp_branca_name = _camp_branca select XF_MAP_LOCATION_DISPLAYNAME;
	
	_players = call XPlayersNumber;
				
	[["%1\n\n%2","STR_MF_M_HAMMER1_3_NAME","STR_MF_M_HAMMER1_3_INTRO"],[],8,10,"PLAIN"] call XfMissionDisplayScreen;	
	sleep 3;
	
	_idx = 1;
	_dist = 0;
	_current = _path select 0;
	while { _dist < 300 } do {
		_dist = _dist + (_current distance (_path select _idx));
		_current = (_path select _idx);
		_idx = _idx + 1;
	};
	
	_vehicles_start = _idx;
	_vehicles_amount = ((ceil(_players / 3)) max 2) min 4;
	
	_pos = _path select _vehicles_start;
	_vehicles_position = _pos;
	_vehicles_start = _vehicles_start + 1;
	_vehicle_types = ["HMMWV_M998_crows_M2_DES_EP1","HMMWV_M1151_M2_DES_EP1","HMMWV_M998_crows_MK19_DES_EP1","HMMWV_M1151_M2_DES_EP1"];
	for [{_l = 0}, {_l < _vehicles_amount}, {_l = _l + 1 }] do {
		_dir = [_pos, (_path select _vehicles_start)] call XfDirTo;
		_pos = _path select _vehicles_start;
		_pos = _pos findEmptyPosition [0,10];
		if (count _pos <= 0) then {_pos = _path select _vehicles_start;};
		_pos set [2, 1.5];
		_vec = [(_vehicle_types select _l),_pos,"REGISTER",[1,2,3,4]] call XfMissionCreateMissionObject;	
		_vec  setPos _pos;	
		_vec  setDir _dir;
		_vec setVelocity [0.5,0,0.5];
		_vec setDamage 0;
		if (_l == 0) then {
			_box_pos = _vec ModelToWorld [3,0,0];
			_box_pos set [2,0];
			DM_Ammo_Box = _box_pos;
			["d_m_box", [DM_Ammo_Box, (nearestObject [DM_Ammo_Box, "AllVehicles"]), "", d_own_side,d_vehicle_drop_box]] call XNetCallEvent;
		};
		_vehicles_start = _vehicles_start + 2;
	};
	[false,["Vehicles", _vehicles_position, "ICON", "ColorBlue", [0.7,0.7],"HUMVEE",0,"hd_flag","",0.8]] call XfMissionMarker;
	
	_enemy_soldiers = [];
	_encounters = (floor((count _path) / 150) min 3);
	_distance_paths = floor((count _path) / (_encounters + 1));
	diag_log Format["(%1)[%2]: %3: %4: %5, %6",diag_tickTime,"chapter3.sqf","XfMissionChapterSetup","Encounters",[_encounters, _distance_paths], Time];
	for [{_k = 1}, {_k <= _encounters}, {_k = _k + 1 }] do {
		_road_block = true;
		_path_idx_start = (_k * _distance_paths);
		_path_idx_end = ((_k + 1) * _distance_paths) - (_distance_paths / 3);
		if (_path_idx_end >= (count _path)) then { _path_idx_end = (count _path) - (_distance_paths / 3); };
		_ambush_pos = [];
		_curr_idx = _path_idx_start;
		_parameters = [d_map_locations];
		_parameters set [count _parameters, [XF_MAP_LOCATION_TYPE,"IN",[XF_MAP_LOCATION_TYPE_TOWN,XF_MAP_LOCATION_TYPE_VILLAGE]]];
		_eligible_towns = _parameters call XfTableFilter;
		while {count _ambush_pos <= 0 && (_curr_idx < _path_idx_end)} do {
			_ambush_pos = _path select _curr_idx;
			if (([_ambush_pos, 4] call XfGetSlope) <= 1.5) then {
				_town_found = false;
				{
					_temp_pos = _x select XF_MAP_LOCATION_CENTER;
					_temp_size = _x select XF_MAP_LOCATION_SIZE;
					if (!_town_found) then { _town_found =[_ambush_pos, [_temp_pos, _temp_size]] call XfPointInCircle; };
				} foreach _eligible_towns;
				if (!_town_found) then {
					_ambush_pos = [];
				};
			} else {
				_ambush_pos = [];
			};
			_curr_idx = _curr_idx + 1;
		};
		// No town or crossroad found
		if (count _ambush_pos <= 0) then {
			_road_block = false;
			_curr_idx = floor(random(_path_idx_end - _path_idx_start)) + _path_idx_start;
			_ambush_pos = _path select _curr_idx;
		};
		_ambush_pos set [2,0];
		_ambush_zone = format["chapter3_ambush_%1",_k];
		_ambush_zone_vis = format["chapter3_ambush_vis_%1",_k];
		_zone_idx = (floor(_curr_idx - 10 + random(20)));
		_ambush_zone_pos = _path select _zone_idx;
		_ambush_zone_dir =[(_path select (_zone_idx - 5)), _ambush_zone_pos] call XfDirTo;;
		diag_log Format["(%1)[%2]: %3: %4: %5, %6",diag_tickTime,"chapter3.sqf","XfMissionChapterSetup","Ambush",[_curr_idx, _zone_idx, _ambush_pos, _ambush_zone_pos], Time];
		[true,[_ambush_zone, _ambush_pos, "ELLIPSE", "ColorRed", [100,100],"",0,"","BDiagonal",0.0001]] call XfMissionMarker;
		[false,[_ambush_zone_vis, _ambush_zone_pos, "ELLIPSE", "ColorRed", [100,150],"",_ambush_zone_dir,"","",1]] call XfMissionMarker;
		
		_ups_params = [_ambush_zone,"noveh","aware"];
		_bunker = objNull;
		_previous_road = _path select (_curr_idx - 5);
		_direction = [_previous_road, _ambush_pos] call XfDirTo;
		if (_road_block) then {
			_previous_road set [2,-0.5];
			_ups_params = [_ambush_zone,"noveh","aware","nomove"];
			_bunker = ["Land_fortified_nest_small_EP1",[_previous_road,_direction],"REGISTER",[],"","NONE"] call XfMissionCreateMissionObject;
			_bunker setDir _direction;
		} else {
			_ups_params = [_ambush_zone,"noveh","aware","ambush2"];
		};
		_grpSoldiers = [d_enemy_side,[_ambush_pos,20],_ups_params,0] call XfMissionCreateFootmenGroup;
		_enemy_soldiers = [_enemy_soldiers, (units _grpSoldiers)] call XfArrayPushStack;
		if (_players >= 10) then {
			_grpSoldiers = [d_enemy_side,[_ambush_pos,20],_ups_params,0] call XfMissionCreateFootmenGroup;
			_enemy_soldiers = [_enemy_soldiers, (units _grpSoldiers)] call XfArrayPushStack;
		};
		if (!isnull _bunker) then {
			_soldier = (units _grpSoldiers) select 0;
			_soldier setPosASL (getPosASL _bunker);
			_soldier setDir (180 + _direction);
			_soldier disableAI "MOVE";
		};
	};
	// for [{_i = 1}, {_i <= _encounters}, {_i = _i + 1 }] do {
		// _path_idx = (_i * _distance_paths) - 30 + floor(random(60));
		// if (_path_idx >= (count _path)) then { _path_idx = (count _path) - 2; };
		// _ambush_pos = [];
		// _curr_idx = _path_idx;
		// while {count _ambush_pos <= 0} do {
			// _ambush_pos = _path select _curr_idx;
			// if (([_ambush_pos, 4] call XfGetSlope) > 1) then {
				// if ((_path_idx - _curr_idx) < 50) then {
					// _ambush_pos = [];
				// } else {
					// _ambush_pos = _path select _path_idx;
				// };
				// _curr_idx = _curr_idx - 1;
			// };
		// };
		// _ambush_pos set [2,0];
		// _ambush_zone = format["chapter3_ambush_%1",_i];
		// [false,[_ambush_zone, _ambush_pos, "ELLIPSE", "ColorRed", [80,80],"",0,"","BDiagonal",0.5]] call XfMissionMarker;
		// _grpSoldiers = [d_enemy_side,[_ambush_pos,20],[_ambush_zone,"noveh","aware","nomove"],0] call XfMissionCreateFootmenGroup;
		// _enemy_soldiers = [_enemy_soldiers, (units _grpSoldiers)] call XfArrayPushStack;
		// if (_players >= 10) then {
			// _grpSoldiers = [d_enemy_side,[_ambush_pos,20],[_ambush_zone,"noveh","aware","nomove"],0] call XfMissionCreateFootmenGroup;
			// _enemy_soldiers = [_enemy_soldiers, (units _grpSoldiers)] call XfArrayPushStack;
		// };
		// _previous_road = _path select (_path_idx - 5);
		// _direction = [_previous_road, _ambush_pos] call XfDirTo;
		// _bunker = ["Land_fortified_nest_small_EP1",[_previous_road,_direction],"REGISTER",[],"","NONE"] call XfMissionCreateMissionObject;
		// _bunker setDir _direction;
		// _soldier = (units _grpSoldiers) select 0;
		// _soldier setPosASL (getPosASL _bunker);
		// _soldier setDir (180 + _direction);
		// _soldier disableAI "MOVE";
	// };
	DM_Target = _enemy_soldiers;
	DM_Chapter_Location = _camp_branca;
	DM_Chapter_Position = _camp_branca_pos;
	
	// This indicates where the mission takes place
	[_camp_branca_pos,_camp_branca_size,_camp_branca_name] call XfMissionCurrentPosition;

	[true,["chapter3_branca", _camp_branca_pos, "ELLIPSE", "ColorBlue", [_camp_branca_size,_camp_branca_size],"",0,"","BDiagonal",0.0001]] call XfMissionMarker;
	[false,["chapter3_branca_dest", _camp_branca_pos, "ICON", "ColorBlue", [1,1],_camp_branca_name,0,"hd_end","",0.7]] call XfMissionMarker;
	["OpenTheRoad","STR_MF_M_HAMMER1_3_TASK", ["STR_MF_M_HAMMER1_3_TASK_DESC",_camp_branca_name],"",[],"Created"] call XfMissionTask;

	for [{_l = 0}, {_l < 6}, {_l = _l + 1}] do {
		_grpSoldiers = [d_own_side,[_camp_branca_pos,_camp_branca_size],["chapter3_branca","noveh","aware","buildings"],0] call XfMissionCreateFootmenGroup;
	};
	
	_vec_types = ["M2A3_EP1","M1128_MGS_EP1","M2A3_EP1","M1126_ICV_M2_EP1","LandRover_Special_CZ_EP1","HMMWV_Ambulance_DES_EP1","HMMWV_M998A2_SOV_DES_EP1","HMMWV_M998A2_SOV_DES_EP1","HMMWV_M998_crows_M2_DES_EP1"];
	_idx = (count _branca_camp_vecs) min (count _vec_types);
	for [{_l = 0}, {_l < _idx}, {_l = _l + 1}] do {
		_vec = [(_vec_types select _l),(_branca_camp_vecs select _l),"REGISTER",[1,2,3,4]] call XfMissionCreateMissionObject;
	};
	
	_vec_types = ["Mi171Sh_rockets_CZ_EP1","AH64D_EP1","MH6J_EP1"];
	_idx = (count _branca_camp_heli) min (count _vec_types);
	for [{_l = 0}, {_l < _idx}, {_l = _l + 1}] do {
		_vec = [(_vec_types select _l),(_branca_camp_heli select _l),"REGISTER",[1,2,3,4]] call XfMissionCreateMissionObject;
	};
};

XfMissionChapterSuccess={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter3.sqf","XfMissionChapterSuccess","Starting"];
	"STR_MF_M_HAMMER1_3_SUCCESS" call XfMissionMessageToAll;
	DM_Mission_Chapter_Success = 1;
};

XfMissionChapterFailure={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter3.sqf","XfMissionChapterFailure","Starting"];
	"STR_MF_MISSIONFAILURE2" call XfMissionMessageToAll;
	DM_Mission_Chapter_Success = -1;
};

// Self-explanatory
XfMissionChapterCleanUp={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter3.sqf","XfMissionChapterCleanUp","Starting"];
	// Giving an empty position places the teleporter back to the hangar, closing the hangar.
	[[],0] call XfMissionPlaceStartTeleporter;
	[] call XfMissionCleanMarkers;
	[] call XfMissionCleanTriggers;
	[] call XfMissionCleanTasks;
};

DM_Mission_Chapter_Compiled = true;